import { game } from 'cc';
import { BaseModule } from './base/BaseModule';
import { GameEvent } from '../../game/configs/GameEvent';
import { GameFramework } from './base/GameFramework';

/**
 * 状态接口
 */
export interface IState {
    /**
     * 状态名称
     */
    name: string;

    /**
     * 进入状态时调用
     * @param fromState 来自哪个状态
     * @param data 传递的数据
     */
    onEnter?(fromState: IState | null, data?: any): void;

    /**
     * 更新状态时调用
     * @param deltaTime 帧间隔时间
     */
    onUpdate?(deltaTime: number): void;

    /**
     * 退出状态时调用
     * @param toState 要切换到哪个状态
     * @param data 传递的数据
     */
    onExit?(toState: IState | null, data?: any): void;
}

/**
 * 状态转换条件接口
 */
export interface ITransitionCondition {
    /**
     * 条件名称
     */
    name: string;

    /**
     * 检查条件是否满足
     */
    check(): boolean;
}

/**
 * 状态转换接口
 */
export interface ITransition {
    /**
     * 条件
     */
    condition: ITransitionCondition;

    /**
     * 目标状态
     */
    toState: IState;

    /**
     * 转换时传递的数据
     */
    data?: any;
}

/**
 * 有限状态机类
 */
export class FSMSystem extends BaseModule {
    /**
     * 所有状态
     */
    private _states: Map<string, IState> = new Map();

    /**
     * 状态转换表
     */
    private _transitions: Map<string, ITransition[]> = new Map();

    /**
     * 当前状态
     */
    private _currentState: IState | null = null;

    /**
     * 上一个状态
     */
    private _previousState: IState | null = null;

    /**
     * 状态机是否运行中
     */
    private _isRunning: boolean = false;

    constructor() {
        super();
    }

    /**
     * 初始化状态机
     */
    init(): void {
        this._isRunning = true;
        console.log("FiniteStateMachine initialized");
        GameFramework.event.on(GameEvent.GAME_UPDATE, this.update, this)
    }

    /**
     * 关闭状态机
     */
    shutdown(): void {

        GameFramework.event.off(GameEvent.GAME_UPDATE, this.update, this)
        this._isRunning = false;
        
        // 退出当前状态
        if (this._currentState && this._currentState.onExit) {
            this._currentState.onExit(null);
        }
        
        this._states.clear();
        this._transitions.clear();
        this._currentState = null;
        this._previousState = null;
        
        console.log("FiniteStateMachine shutdown");
    }

    /**
     * 添加状态
     * @param state 状态
     */
    addState(state: IState): void {
        if (this._states.has(state.name)) {
            console.warn(`State ${state.name} already exists`);
            return;
        }
        
        this._states.set(state.name, state);
        
        // 如果是第一个状态，则设置为当前状态
        if (!this._currentState) {
            this._currentState = state;
            if (state.onEnter) {
                state.onEnter(null);
            }
        }
    }

    /**
     * 移除状态
     * @param stateName 状态名称
     */
    removeState(stateName: string): void {
        if (!this._states.has(stateName)) {
            console.warn(`State ${stateName} does not exist`);
            return;
        }
        
        // 如果要移除的是当前状态，先切换到其他状态
        if (this._currentState && this._currentState.name === stateName) {
            // 尝试切换到第一个可用状态
            for (const [name, state] of this._states) {
                if (name !== stateName) {
                    this.changeState(name);
                    break;
                }
            }
        }
        
        this._states.delete(stateName);
        
        // 移除相关的转换
        this._transitions.delete(stateName);
        for (const transitions of this._transitions.values()) {
            const index = transitions.findIndex(t => t.toState.name === stateName);
            if (index !== -1) {
                transitions.splice(index, 1);
            }
        }
    }

    /**
     * 添加状态转换
     * @param fromStateName 起始状态名称
     * @param transition 转换条件和目标状态
     */
    addTransition(fromStateName: string, transition: ITransition): void {
        if (!this._states.has(fromStateName)) {
            console.warn(`State ${fromStateName} does not exist`);
            return;
        }
        
        if (!this._states.has(transition.toState.name)) {
            console.warn(`Target state ${transition.toState.name} does not exist`);
            return;
        }
        
        if (!this._transitions.has(fromStateName)) {
            this._transitions.set(fromStateName, []);
        }
        
        this._transitions.get(fromStateName)!.push(transition);
    }

    /**
     * 移除状态转换
     * @param fromStateName 起始状态名称
     * @param conditionName 条件名称
     */
    removeTransition(fromStateName: string, conditionName: string): void {
        if (!this._transitions.has(fromStateName)) {
            console.warn(`No transitions from state ${fromStateName}`);
            return;
        }
        
        const transitions = this._transitions.get(fromStateName)!;
        const index = transitions.findIndex(t => t.condition.name === conditionName);
        if (index !== -1) {
            transitions.splice(index, 1);
        }
    }

    /**
     * 改变状态
     * @param stateName 目标状态名称
     * @param data 传递的数据
     * @returns 是否成功切换状态
     */
    changeState(stateName: string, data?: any): boolean {
        if (!this._isRunning) {
            console.warn("FSM is not running");
            return false;
        }
        
        if (!this._states.has(stateName)) {
            console.warn(`State ${stateName} does not exist`);
            return false;
        }
        
        const targetState = this._states.get(stateName)!;
        
        // 如果目标状态就是当前状态，则不处理
        if (this._currentState && this._currentState.name === stateName) {
            return false;
        }
        
        // 退出当前状态
        if (this._currentState && this._currentState.onExit) {
            this._currentState.onExit(targetState, data);
        }
        
        // 保存上一个状态
        this._previousState = this._currentState;
        
        // 进入新状态
        const fromState = this._currentState;
        this._currentState = targetState;
        if (this._currentState.onEnter) {
            this._currentState.onEnter(fromState, data);
        }
        
        return true;
    }

    /**
     * 获取当前状态
     */
    getCurrentState(): IState | null {
        return this._currentState;
    }

    /**
     * 获取上一个状态
     */
    getPreviousState(): IState | null {
        return this._previousState;
    }

    /**
     * 检查当前是否为指定状态
     * @param stateName 状态名称
     */
    isInState(stateName: string): boolean {
        return this._currentState ? this._currentState.name === stateName : false;
    }

    /**
     * 更新状态机
     * @param deltaTime 帧间隔时间
     */
    update(deltaTime: number): void {
        if (!this._isRunning) {
            return;
        }
        
        // 更新当前状态
        if (this._currentState && this._currentState.onUpdate) {
            this._currentState.onUpdate(deltaTime);
        }
        
        // 检查状态转换条件
        this.checkTransitions();
    }

    /**
     * 检查状态转换条件
     */
    private checkTransitions(): void {
        if (!this._currentState) {
            return;
        }
        
        const currentStateName = this._currentState.name;
        if (!this._transitions.has(currentStateName)) {
            return;
        }
        
        const transitions = this._transitions.get(currentStateName)!;
        for (const transition of transitions) {
            if (transition.condition.check()) {
                this.changeState(transition.toState.name, transition.data);
                break;
            }
        }
    }

    /**
     * 启动状态机
     */
    start(): void {
        this._isRunning = true;
    }

    /**
     * 停止状态机
     */
    stop(): void {
        this._isRunning = false;
    }
}